package com.xhwl.centiotdata.handler.account.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.account.AccountFactory;
import com.xhwl.centiotdata.handler.account.AccountHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.service.cent.IAuthAccountCentService;
import com.xhwl.centiotdata.suppliersystem.itc.UserItcHandler;
import com.xhwl.common.dto.cent.sdata.AccountDTO;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.personnel.StaffDTO;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangyiling
 * @description 同步主数据到蒙牛ITC会议
 * @date 2022/9/16 10:31
 */
@Slf4j
@Service
public class AccountItcHandler extends AccountHandler {
    @Autowired
    private UserItcHandler userItcHandler;

    @Resource
    private IOrgInfoService iOrgInfoService;

    @Autowired
    private IAuthAccountCentService authAccountCentService;

    @Override
    public String syncUser(PedestrianIntegrationConfigDTO configDTO, StaffDTO staffDTO) {
        String userOpenId = "";
        try {
            // 新增住户人员信息
            //userOpenId = userItcHandler.addPerson(staffDTO, configDTO);
            log.info("新增住户人员信息：{}", userOpenId);

        } catch (Exception e) {
            log.error("userItcHandler:addPerson fail：{}", e.toString());
        }
        return userOpenId;
    }

    @Override
    public void add(StaffDTO dto, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        handleAdd(dto, projectId, integrationConfig);
    }

    private void handleAdd(StaffDTO staffDTO, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        if (null != integrationConfig) {//itc人事系统已同步
            try {
                //StaffDTO staffDTO = iAccountCentService.detail(null, staff.getEnterpriseId().get(0), staff.getAccountId());
                JSONObject properties = integrationConfig.getProperties();
                Integer productId = integrationConfig.getProductId();
                PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
                config.setIpAndPort(properties.getString("ipAndPort"));
                config.setAk(properties.getString("ak"));
                config.setSk(properties.getString("sk"));
                config.setProductId(productId);
                config.setLoginName(properties.getString("loginName"));
                config.setPassword(properties.getString("password"));
                config.setProjectId(projectId);
                if (!CollectionUtils.isEmpty(staffDTO.getOrgIds())) {
                    List<OrgInfo> orgInfoList = iOrgInfoService.getList(productId, staffDTO.getOrgIds());
                    List<Integer> thirdList = orgInfoList.stream().map(OrgInfo::getOrgIndexCode).filter(StringUtils::isNotEmpty).map(Integer::parseInt).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(thirdList)) {
                        String positionName = "普通员工";
                        if (StringUtils.isNotEmpty(staffDTO.getPositionName())) {
                            positionName = staffDTO.getPositionName();
                        }
                        staffDTO.setLoginName("mn" + staffDTO.getAccountId() + "-" + positionName);
                        staffDTO.setPassword("xh" + staffDTO.getPhone());
                        staffDTO.setOrgIds(thirdList);
                        staffDTO.setId(null);
                        log.error("待添加账号信息：{}", staffDTO);
                        String userOpenId = userItcHandler.addPerson(staffDTO, config);
                        authAccountCentService.save(projectId, staffDTO.getAccountId(), userOpenId, null, productId);
                    }
                } else {
                    log.info("员工组织不存在 不能同步");
                }
            } catch (Exception e) {
                log.error("配置信息：{}", integrationConfig);
                log.error("同步itc平台异常", e);
            }
        }
    }

    @Override
    public void update(StaffDTO staffDTO, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        if (null != integrationConfig) {//itc人事系统同步
            //员工组织
            AuthAccountMapping authAccount = authAccountCentService.query(projectId, staffDTO.getAccountId(), integrationConfig.getProductId());
            if (null != authAccount && StringUtils.isNotEmpty(authAccount.getOpenId())) {
                JSONObject properties = integrationConfig.getProperties();
                Integer productId = integrationConfig.getProductId();
                PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
                config.setIpAndPort(properties.getString("ipAndPort"));
                config.setAk(properties.getString("ak"));
                config.setSk(properties.getString("sk"));
                config.setProductId(productId);
                config.setLoginName(properties.getString("loginName"));
                config.setPassword(properties.getString("password"));
                config.setProjectId(projectId);
                if (!CollectionUtils.isEmpty(staffDTO.getOrgIds())) {
                    List<OrgInfo> orgInfoList = iOrgInfoService.getList(productId, staffDTO.getOrgIds());
                    List<Integer> thirdList = orgInfoList.stream().map(OrgInfo::getOrgIndexCode).filter(StringUtils::isNotEmpty).map(Integer::parseInt).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(thirdList)) {
                        String positionName = "普通员工";
                        if (StringUtils.isNotEmpty(staffDTO.getPositionName())) {
                            positionName = staffDTO.getPositionName();
                        }
                        staffDTO.setLoginName("mn" + staffDTO.getAccountId() + "-" + positionName);
                        staffDTO.setPassword("xh" + staffDTO.getPhone());
                        staffDTO.setOrgIds(thirdList);
                        staffDTO.setId(Integer.parseInt(authAccount.getOpenId()));
                        userItcHandler.addPerson(staffDTO, config);
                    }
                } else {
                    log.info("员工组织不存在 不能更新");
                }
            } else {
                handleAdd(staffDTO, projectId, integrationConfig);
            }
        }
    }

    @Override
    public void delete(AccountDTO accountDTO, Integer projectId, DeviceProjSupplierCategory integrationConfig) {
        if (null != integrationConfig) {
            //查询关联表
            Integer productId = integrationConfig.getProductId();
            AuthAccountMapping authAccount = authAccountCentService.query(projectId, accountDTO.getId(), productId);
            if (null != authAccount && StringUtils.isNotEmpty(authAccount.getOpenId())) {
                JSONObject properties = integrationConfig.getProperties();
                PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
                config.setIpAndPort(properties.getString("ipAndPort"));
                config.setAk(properties.getString("ak"));
                config.setSk(properties.getString("sk"));
                config.setProductId(productId);
                config.setLoginName(properties.getString("loginName"));
                config.setPassword(properties.getString("password"));
                config.setProjectId(projectId);
                userItcHandler.deleteUser("mn" + accountDTO.getId(), config);
                authAccountCentService.deleteAccountMapping(projectId, accountDTO.getId(), authAccount.getOpenId(), productId);
            }
        }
    }

    @Override
    public void afterPropertiesSet() {
        AccountFactory.register(ProductEnum.ITC_BOARDROOM.getId(), this);
        log.info("ITC会议账号管理注册成功");
    }
}
